package cn.xiqi.cms.hibernate.DAO;

import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.xiqi.cms.hibernate.beans.Cominfo;

public class CominfoDAOImpl implements CominfoDAO {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public List<Cominfo> select(Map values) {
		Session session = null;
		List<Cominfo> records = null;
		Query query = null;
		String type;
		int page = 0;
		int size = 0;
		
		try {
			session = HibernateSessionFactory.currentSession();
			type = (String)values.get("type");
			if(type.equals("id")){
				query = session.createQuery("from Cominfo where comID=?");
				query.setInteger(0, (Integer)values.get("id"));
			}else if(type.equals("all")) {
				query = session.createQuery("from Cominfo");
			}
			if(values.get("page") != null && (int)values.get("page") != 0 ){
				page = (int)values.get("page");
				size = (int)values.get("size");
				query.setFirstResult((page - 1) * size);
				query.setMaxResults(size);
			}
		}catch (Exception e) {
			throw e;
		} finally {
			records = query.list();
			HibernateSessionFactory.closeSession();
		}
		return records;
	}

	@Override
	public boolean update(Cominfo record) {
		Session session = null;
		Transaction tx = null;
		boolean b =true;
		
		try {
			session = HibernateSessionFactory.currentSession();
			tx = session.beginTransaction();
			session.update(record);
			tx.commit();
		}
		catch (HibernateException e){
			b = false;
			throw e;
		}
		finally {
			if(tx!=null){
				tx.rollback();
			}
			HibernateSessionFactory.closeSession();
		}
		return b;
	}

	@Override
	public int insert(Cominfo record) {
		Session session = null;
		Transaction tx = null;
		int id = 0;
		
		try {
			session = HibernateSessionFactory.currentSession();
			tx = session.beginTransaction();
			session.save(record);
			id = record.getComID();
			tx.commit();
		}
		catch (HibernateException e){
			throw e;
		}
		finally {
			if(tx!=null){
				tx.rollback();
			}
			HibernateSessionFactory.closeSession();
		}
		return id;
	}

	@Override
	public boolean delete(Cominfo record) {
		Session session = null;
		Transaction tx = null;
		boolean b = true;
		
		try {
			session = HibernateSessionFactory.currentSession();
			tx = session.beginTransaction();
			session.delete(record);
			tx.commit();
		}
		catch (HibernateException e) {
			b = false;
			throw e;
		}
		finally {
			if(tx!=null) {
				tx.rollback();
			}
			HibernateSessionFactory.closeSession();
		}
		return b;
	}

}
